import React, {PropTypes} from 'react';

import {Button, Icon} from 'antd';

/**
* 自定义按钮BUTTON，用于统一权限控制，方便维护
*/
export default class IButton extends React.Component {
	constructor(props) {
    super(props);
    const hasPermission = localStorage.getItem('permission')
    this.permission = hasPermission ? hasPermission.split(",") : []
    this.state = {
      visible: true
    };
  }

  //判断是否有权限，
  //this.permission为用户拥有的权限，每次登录或者刷新浏览器会同步服务端的权限
  isAuth = (perm) => {
    let flag = false;
    const cacheFlag = 'perm:' + perm;
    const cacheAuth = localStorage.getItem(cacheFlag);
    if(cacheAuth === 'true') {
      return true;
    } else if(cacheAuth === 'false') {
      return false;
    }
    for (let i = 0; i < this.permission.length; i++) {
      if(this.permission[i] === perm) {
        flag = true;
        break;
      }
    }
    //本地缓存权限，这样就不用每次都去循环判断，刷新浏览器时，清空本地缓存
    localStorage.setItem(cacheFlag, flag)
    return flag;
  }

	componentWillMount() {
		const {perm} = this.props;
		if(perm) {
			this.setState({
				visible:this.isAuth(perm)
			});
		}
	}

	render() {
		const {icon, disabled, children, type, a, onClick} = this.props;
		const {visible} = this.state;
		if(visible) {
			if(a) {
				if(onClick) {
					return <a href="javascript:void(0)" disabled={disabled} onClick={onClick}>{children}</a>;
				} else {
					return <a href="javascript:void(0)" disabled={disabled}>{children}</a>;
				}

			} else {
				return (
					<Button size="default" onClick={onClick} disabled={disabled} type={type} icon={icon}  style={{marginRight:'8px'}}>{children}</Button>
				);
			}
		} else {
			return null
		}

	}
}
